<?php

namespace Frieza\Modules\Circle\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Circle\CircleBlack;
use Doraemon\model\Circle\CircleBlack as mCircleBlack;
use Doraemon\model\Circle\CircleOperationLog as mCircleOperationLog;
use Doraemon\service\Circle\CircleBlack as sCircleBlack;
use Doraemon\service\Circle\CircleOperationLog as sCircleOperationLog;
use Encore\Admin\Layout\Content;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;

class CircleBlackController
{
    public function index(Content $content, Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $uid = $request->input('uid', 0);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = [];
        if ($uid) {
            $where = ['uid' => $uid];
        }
        $data = sCircleBlack::getListForAdmin($where, $limit);
        $data['list'] = empty($data['list']) ? [] : sCircleBlack::format($data['list']);
        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => $pageSize,
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('uid', 'uid');
                });
            });
            $grid->column('uid', 'uid');
            $grid->column('nick', '昵称')->display(function ($released) {
                return $this->user_info['nick'];
            });
            $grid->column('addtime', '拉黑时间')->display(function ($released) {
                if ($released) {
                    return date('Y-m-d H:i:s', $released);
                }
                return '';
            });

            $grid->column('remove_num', '被移除圈子的次数');
            $grid->column('admin_id', '操作人')->display(function ($adminId) {
                return $this->join_way == 1 ? Admin::user()->find($adminId)->name : '';
            });

            $grid->actions(function ($actions) {
                $actions->row->setKeyName('id');
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                // 去掉查看
                $actions->disableView();
                $desc = ($actions->row->status == 1) ? '取消拉黑' : '拉黑';
                $value = ($actions->row->status == 1) ? 9 : 1;
                $actions->prepend('<p><a class="setBlack label  label-info" data-uid="' . $actions->row->uid . '" data-status = "' . $value . '" href="javascript:void(0);">' . $desc . '</a></p>');
            });
        });
        Admin::script($this->setScript());
        return $content
            ->header('黑名单用户列表')
            ->breadcrumb(['text' => '黑名单用户列表', 'url' => '/admin/circle/black'])
            ->body($listGrid);
    }

    /**
     * 手动操作黑名单
     *
     * @param Request $request
     * @return JsonResponse
     */
    public static function changeBlack(Request $request)
    {
        $uid = $request->input('uid');
        $status = $request->input('status');
        if (mCircleBlack::STATUS_NORMAL == $status) {//新增
            $result = sCircleBlack::joinBlackList($uid, Admin::user()->id);
            //记录操作日志
            $event = \Doraemon\model\Circle\CircleOperationLog::CIRCLE_BLACK;
            sCircleOperationLog::addLog(0, '', $event, Admin::user()->id, mCircleOperationLog::SOURCE_ADMIN, $uid);
        } else {
            $result = sCircleBlack::removeBlackList($uid);
        }
        $msg = empty($result) ? ['status' => 0, 'message' => '操作'] : ['status' => 1, 'message' => '操作成功'];
        return response()->json($msg);
    }

    /**
     * @return string
     */
    private function setScript()
    {
        return <<<SCRIPT
         $('.setBlack').unbind('click').click(function() {
            var uid = $(this).attr('data-uid');
            var status = $(this).attr('data-status');
            var that = $(this)
          
            let url = '/admin/circle/changeBlack';
            let params = {
                status:status,
                uid:uid
            };
            if(1 == status){
              var title = '拉黑后该用户将无法加入任何圈子，其发布的所有圈子内容将全部被移出住友圈且无法恢复，确定拉黑吗？';
              var desc = '取消拉黑';
            }else{
              var title = '是否取消拉黑';
              var desc = '拉黑';
            }
            swal({
                title: title,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                   $.post(url, params , function (result) {              
                         if (result.status == 1){
                            if(status == 9){
                                layer.msg(result.message);
                                setTimeout(function () {
                                    parent.window.location.reload();
                                }, 1000);
                            }else{
                                that.attr('data-status',9)
                                that.text('取消拉黑')
                                layer.msg(result.message); 
                            }                                                        
                        } else {
                            layer.msg(result.message);
                        }
                    });
                }
            });
            
        });
        SCRIPT;
    }
}